/*
 * @lc app=leetcode.cn id=105 lang=cpp
 *
 * [105] 从前序与中序遍历序列构造二叉树
 */

#include <limits.h>

#include <iostream>
#include <map>
#include <unordered_map>
#include <queue>
#include <set>
#include <stack>
#include <vector>
using namespace std;

struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode *left, TreeNode *right)
        : val(x), left(left), right(right) {}
};

// @lc code=start
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    unordered_map<int, int> index;

    TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
        int length = preorder.size();
        
        // 构造映射表，从中序遍历节点的值映射到节点下标
        for (int i = 0; i < length; i++) {
            index[inorder[i]] = i;
        }
        
        return buildSubTree(preorder, inorder, 0, length - 1, 0, length - 1);
    }

    TreeNode* buildSubTree(vector<int>& preorder, vector<int>& inorder, int preorder_left, int preorder_right, int inorder_left, int inorder_right) {
        if (preorder_right < preorder_left) return nullptr;
        
        // 前序遍历中定位根节点，即第一个节点
        int preorder_root = preorder_left;
        // 中序遍历中定位根节点
        int inorder_root = index[preorder[preorder_root]];

        // 构造根节点
        TreeNode* root = new TreeNode(preorder[preorder_root]);

        // 计算左子树中节点数量
        int size_left_subtree = inorder_root - inorder_left;
        root->left = buildSubTree(preorder, inorder, preorder_left + 1, preorder_left + size_left_subtree, inorder_left, inorder_root - 1);
        root->right = buildSubTree(preorder, inorder, preorder_left + size_left_subtree + 1, preorder_right, inorder_root + 1, inorder_right);

        return root;
    }
};
// @lc code=end

